package org.black.missedCall2;

import java.util.ArrayList;

import org.black.missedCall2.object.CallInformation;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.CallLog;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.google.ads.AdRequest;
import com.google.ads.AdView;

public class MissedCallActivity extends ActionBarActivity
		implements
		MissedCallRowMenuDialogFragment.MissedCallRowMenuDialogListener,
		MissedCallFontSizeDialogFragment.MissedCallFontSizeDialogListener,
		MissedCallConfirmClearMissedCallDialogFragment.MissedCallConfirmClearMissedCallDialogListener {
	private Handler handler;
	private ListView listView;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.missed_call);

		AdView adView = (AdView) this.findViewById(R.id.adView);
		adView.loadAd(new AdRequest());

		TextView noMissedCallTextView = (TextView) findViewById(R.id.noMissedCallView);
		listView = (ListView) findViewById(R.id.missedCalllistView);
		listView.setEmptyView(noMissedCallTextView);
		listView.setDividerHeight(1);
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				MissedCallRowMenuDialogFragment missedCallRowDialogFragment = new MissedCallRowMenuDialogFragment();
				long contactId = -1;
				String phoneNumber = "-1";

				Object object = parent.getItemAtPosition(position);
				if (object != null) {
					CallInformation callInformation = (CallInformation) object;
					phoneNumber = callInformation.getNumber();
					if (callInformation.getContactId() != null) {
						contactId = callInformation.getContactId();
					}
				}

				Bundle dialogBundle = new Bundle();
				dialogBundle.putLong(MissedCallConstant.CONTACT_ID, contactId);
				dialogBundle.putString(MissedCallConstant.PHONE_NUMBER,
						phoneNumber);
				dialogBundle.putInt(MissedCallConstant.ROW_POSITION, position);

				missedCallRowDialogFragment.setArguments(dialogBundle);
				missedCallRowDialogFragment.show(getSupportFragmentManager(),
						"dialog");
			}
		});
		MissedCallAdapter missedCallAdapter = new MissedCallAdapter(this);
		listView.setAdapter(missedCallAdapter);

		this.handler = new Handler(new MissedCallListCallback(this));
	}

	@Override
	protected void onResume() {

		super.onResume();
		Cursor cursor = getContentResolver().query(CallLog.Calls.CONTENT_URI,
				null, CallLog.Calls.TYPE + " = " + CallLog.Calls.MISSED_TYPE,
				null, CallLog.Calls.DATE + " DESC");
		ArrayList<CallInformation> callInformations = new ArrayList<CallInformation>();
		if (cursor.moveToFirst()) {
			do {
				Long callId = cursor.getLong(cursor
						.getColumnIndex(CallLog.Calls._ID));
				String number = cursor.getString(cursor
						.getColumnIndex(CallLog.Calls.NUMBER));
				String name = cursor.getString(cursor
						.getColumnIndex(CallLog.Calls.CACHED_NAME));
				Long date = cursor.getLong(cursor
						.getColumnIndex(CallLog.Calls.DATE));
				CallInformation callInformation = new CallInformation();
				callInformation.setId(callId);
				callInformation.setNumber(number);
				callInformation.setCachedName(name);
				callInformation.setDate(date);

				callInformations.add(callInformation);
			} while (cursor.moveToNext());
		}
		cursor.close();

		Bundle bundle = new Bundle();
		bundle.putSerializable(MissedCallConstant.CALLS, callInformations);
		Message message = handler.obtainMessage();
		message.setData(bundle);
		handler.sendMessage(message);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.missed_call_main_activity_actions, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_delete_call_log:
			SharedPreferences sharedPreferences = PreferenceManager
					.getDefaultSharedPreferences(getApplicationContext());
			
			boolean clearRecordsDoNotAskAgainValue = sharedPreferences
					.getBoolean(
							getString(R.string.do_not_ask_me_again_preference_key),
							MissedCallConfirmClearMissedCallDialogFragment.DEFAULT_DO_NO_ASK_ME_AGAIN_VALUE);

			MissedCallConfirmClearMissedCallDialogFragment missedCallConfirmClearMissedCallDialogFragment = new MissedCallConfirmClearMissedCallDialogFragment();
			if (clearRecordsDoNotAskAgainValue == false) {
				missedCallConfirmClearMissedCallDialogFragment.show(
						getSupportFragmentManager(),
						MissedCallConfirmClearMissedCallDialogFragment.TAG);
			} else {
				this.confirmToDeleteAllMissedCallRecords();
			}
			return true;
		case R.id.menu_font_size:
			MissedCallFontSizeDialogFragment missedCallFontSizeDialogFragment = new MissedCallFontSizeDialogFragment();
			missedCallFontSizeDialogFragment.show(getSupportFragmentManager(),
					MissedCallFontSizeDialogFragment.TAG);
			return true;
		case R.id.menu_settings:
			Intent intent = new Intent();
			Bundle extras = new Bundle();
			intent.setClass(MissedCallActivity.this,
					MissedCallPreferenceActivity.class);
			intent.putExtras(extras);
			startActivity(intent);
			Log.i(MissedCallConstant.APP_TAG,
					"Switch to MissedCallPreferenceActivity.");
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onChoosingDeleteSpecificRecord(DialogFragment dialog,
			int position) {
		Object itemObject = this.listView.getItemAtPosition(position);
		CallInformation callInformation = (CallInformation) itemObject;
		getContentResolver().delete(CallLog.Calls.CONTENT_URI,
				CallLog.Calls._ID + " = ?",
				new String[] { callInformation.getId().toString() });
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter != null) {
			MissedCallAdapter missedCallAdapter = (MissedCallAdapter) listAdapter;
			missedCallAdapter.removeItem(callInformation);
			missedCallAdapter.notifyDataSetChanged();
		}

	}

	@Override
	public void onChooseingDeleteAllRecordFromTheSameNumber(
			DialogFragment dialog, String phoneNumber) {
		getContentResolver().delete(CallLog.Calls.CONTENT_URI,
				CallLog.Calls.NUMBER + " = ?", new String[] { phoneNumber });

		MissedCallAdapter missedCallAdapter = (MissedCallAdapter) listView
				.getAdapter();
		int missedCallListCount = missedCallAdapter.getCount();
		for (int i = missedCallListCount - 1; i >= 0; i--) {
			CallInformation callInformation = (CallInformation) missedCallAdapter
					.getItem(i);
			if (callInformation.getNumber().equals(phoneNumber)) {
				missedCallAdapter.removeItem(callInformation);
				missedCallAdapter.notifyDataSetChanged();
			}
		}

	}

	@Override
	public void onStopSeeking(int seekBarPosition) {
		int count = listView.getAdapter().getCount();
		float scale = (seekBarPosition / (float) MissedCallFontSizeDialogFragment.SEEK_BAR_MAX_VALUE) + 1;
		float headerSize = MissedCallConstant.FONT_SIZE_DEFAULT_HEADER * scale;
		float defaultSize = MissedCallConstant.FONT_SIZE_DEFAULT * scale;
		for (int i = 0; i < count; i++) {
			View view = listView.getChildAt(i);
			if (view != null) {
				TextView nameTextView = (TextView) view
						.findViewById(R.id.missedCallName);
				nameTextView
						.setTextSize(TypedValue.COMPLEX_UNIT_SP, headerSize);
				TextView numberTextView = (TextView) view
						.findViewById(R.id.missedCallNumber);
				TextView dateTimeTextView = (TextView) view
						.findViewById(R.id.missedCallDateTime);
				numberTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP,
						defaultSize);
				dateTimeTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP,
						defaultSize);
			}
		}

	}

	@Override
	public void confirmToDeleteAllMissedCallRecords() {
		getContentResolver().delete(CallLog.Calls.CONTENT_URI,
				CallLog.Calls.TYPE + " = " + CallLog.Calls.MISSED_TYPE, null);

		MissedCallAdapter missedCallAdapter = (MissedCallAdapter) listView
				.getAdapter();
		missedCallAdapter.reset();
		missedCallAdapter.notifyDataSetChanged();

	}
}